﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using geoCRM_Services.BusinessEntities;
using System.Data.Linq;

namespace geoCRM_Services.DataAccess
{
    public class ContactDataAccess: IContactDataAccess
    {
        
        #region IContactDataAccess Members
        internal ContactDataAccess()
        {

        }
        public IEnumerable<geoCRM_Services.BusinessEntities.Contact> GetContacts(int PageIndex, int PageSize)
        {
            ContactDBDataContext db = EagerLoadDataContext();
            var contacts = (from c in db.Contacts.AsEnumerable()
                            orderby c.Lastname, c.Firstname
                            select c).Skip(PageIndex).Take(PageSize);
            return contacts;
        }
        public int GetContactsCount()
        {
            ContactDBDataContext db = new ContactDBDataContext();
            var contactscount = (from c in db.Contacts
                                 select c).Count();
            return contactscount;
            
        }
        public Contact GetContactByID(int SearchedID)
        {
            ContactDBDataContext db = EagerLoadDataContext();
           var contact = (from c in db.Contacts
                                where c.ID == SearchedID
                                select c).Single();
           return contact;
           
        }
        #endregion

        #region HelperMethods
        private static ContactDBDataContext EagerLoadDataContext()
        {
            ContactDBDataContext db = new ContactDBDataContext();
            System.Data.Linq.DataLoadOptions dlo = new DataLoadOptions();
            dlo.LoadWith<Contact>(c => c.Contact_Addresses);
            dlo.LoadWith<Contact>(c => c.ContactType);
            dlo.LoadWith<Contact>(c => c.TitleType);
            dlo.LoadWith<Contact_Address>(ca => ca.Address);
            dlo.LoadWith<Contact_Phone>(cp => cp.Phone);
            db.LoadOptions = dlo;
            return db;
        }

        #endregion
    }
}
